package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.TesseractException;
import org.apache.ibatis.cache.CacheException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author shiminghui
 * @date 2024/11/6 17:31
 * @description: TODO
 */
@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private IArticleClient iArticleClient;
    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 文章审核
     *
     * @param id 自媒体文章id
     */
    @Override
    @Async // 开启多线程
//    @GlobalTransactional // 开启分布式事务
    public void autoScanWmNews(Integer id) {

        // 1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            throw new CacheException("文章不存在");
        }
        // 1.2 判断文章是否审核
        if (!wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())) {
            return;
        }
        // 1.3 获取文章内容和图片
        String content = wmNews.getContent();
        StringBuilder stringBuilder = new StringBuilder();
        ArrayList<String> images = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("text")) {
                stringBuilder.append(map.get("value"));
            }
            if (map.get("type").equals("image")) {
                images.add((String) map.get("value"));
            }
        }

        String[] split = null;
        if (wmNews.getImages() == null || wmNews.getImages().isEmpty()) {
            split = new String[0];
        } else {
            split = wmNews.getImages().split(",");
        }

        images.addAll(Arrays.asList(split));
        List<String> imageList = images.stream().distinct().collect(Collectors.toList());

        // 自定义内容关键词深审核
        boolean isSensitive = handleSensitiveScan(stringBuilder.toString(), wmNews);
        if (!isSensitive) return;


        // 2.审核内容
        boolean isValid = handleContentScan(wmNews, stringBuilder.toString());
        if (!isValid) return;

        // 3.审核图片
        boolean isImageValid = handleImageScan(wmNews, imageList);
        if (!isImageValid) return;

        //审核成功,修改自媒体文章状态
        updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "审核成功,待发布");

        //判断是否需要延时发布
        if (wmNews.getPublishTime() != null && wmNews.getPublishTime().getTime() > new Date().getTime()) {
            // 延时发布
            ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
            executorService.schedule(() -> {
                publishNews(wmNews);
            }, wmNews.getPublishTime().getTime() - new Date().getTime(), TimeUnit.MILLISECONDS);
        } else {
            publishNews(wmNews);
        }
    }

    /**
     * 发布文章
     *
     * @param wmNews
     */
    private void publishNews(WmNews wmNews) {
        // 4.保存app文章信息(远程调用)
        ResponseResult result = saveAppArticle(wmNews);
        if (!result.getCode().equals(200)) {
            log.error("WmNewsAutoScanServiceImpl - 保存app文章信息失败");
            throw new CacheException("WmNewsAutoScanServiceImpl - 保存app文章信息失败");
        }

        // 5.修改自媒体文章状态
        wmNews.setArticleId((Long) result.getData());
        updateWmNews(wmNews, WmNews.Status.PUBLISHED.getCode(), "审核通过");
    }

    /**
     * 处理审核文章内容(自定义敏感词)
     *
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitiveScan(String content, WmNews wmNews) {
        boolean flag = true;

        //获取所有的敏感词
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());

        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);

        //查看文章中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) {
            updateWmNews(wmNews, (short) 2, "当前文章中存在违规内容" + map);
            flag = false;
        }

        return flag;
    }

    /**
     * 保存app文章信息
     *
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        // 属性拷贝
        BeanUtils.copyProperties(wmNews, articleDto);
        // 封面图片
        articleDto.setLayout(wmNews.getType());
        // 设置频道名称
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        articleDto.setChannelName(wmChannel.getName());

        //作者
        articleDto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            articleDto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if (wmNews.getArticleId() != null) {
            articleDto.setId(wmNews.getArticleId());
        }
        articleDto.setCreatedTime(new Date());

        ResponseResult responseResult = iArticleClient.saveArticle(articleDto);
        return responseResult;
    }

    /**
     * 审核图片
     *
     * @param wmNews
     * @param imageList
     * @return
     */
    private boolean handleImageScan(WmNews wmNews, List<String> imageList) {
        if (imageList == null || imageList.isEmpty()) {
            return true;
        }
        // 遍历图片文字审核
        for (String s : imageList) {
            byte[] bytes = fileStorageService.downLoadFile(s);
            //从byte[]转换为butteredImage
            ByteArrayInputStream in = new ByteArrayInputStream(bytes);
            BufferedImage imageFile = null;
            String result = null;
            try {
                imageFile = ImageIO.read(in);
                //识别图片的文字
                result = tess4jClient.doOCR(imageFile);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (TesseractException e) {
                throw new RuntimeException(e);
            }

            //审核是否包含自管理的敏感词
            boolean isSensitive = handleSensitiveScan(result, wmNews);
            if (!isSensitive) {
                return isSensitive;
            }
        }


        // 调用阿里云图片审核接口
        try {
            Map map = greenImageScan.imageScan(imageList);
            if (map != null) {
                if (map.get("message").equals("ok")) {
                    return true;
                }
                if (map.get("riskLevel").equals("high")) {
                    //设置文章状态为审核失败
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "存在违规信息");
                    return false;
                }
                if (map.get("riskLevel").equals("medium")) {
                    //设置文章状态为人工审核
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "存在未知信息,待管理人员审核");
                    return false;
                }
                if (map.get("riskLevel").equals("low")) {
                    return true;
                }
                if (map.get("riskLevel").equals("none")) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("WmNewsAutoScanServiceImpl - 审核失败", e);
            return false;
        }
        return true;
    }

    /**
     * 审核文章内容
     *
     * @param wmNews
     * @param content
     * @return
     */
    private boolean handleContentScan(WmNews wmNews, String content) {
        String title = wmNews.getTitle();
        if (content == null || content.equals("")) {
            return true;
        }
        if (title == null || title.equals("")) {
            return true;
        }
        //调用敏感词审核接口
        try {
            Map map = greenTextScan.greenTextScan(title + "-" + content);
            if (map != null) {
                if (map.get("message").equals("ok")) {
                    return true;
                }
                if (map.get("riskLevel").equals("high")) {
                    //设置文章状态为审核失败
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "存在违规信息");
                    return false;
                }
                if (map.get("riskLevel").equals("medium")) {
                    //设置文章状态为人工审核
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "存在未知信息,待管理人员审核");
                    return false;
                }
                if (map.get("riskLevel").equals("low")) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("WmNewsAutoScanServiceImpl - 审核失败", e);
            return false;
        }
        return true;
    }

    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }
}
